package com.zx.system.block.service.impl;

import com.zx.core.constant.CacheConstants;
import com.zx.core.context.TenantContextHolder;
import com.zx.core.enums.StatusEnum;
import com.zx.core.page.PageInfo;
import com.zx.core.wrapper.ListWrapper;
import com.zx.core.wrapper.ObjectWrapper;
import com.zx.core.wrapper.PageWrapper;
import com.zx.core.wrapper.ResponseWrapper;
import com.zx.feign.client.dto.DictDataDTO;
import com.zx.redis.block.service.RedisBlockService;
import com.zx.security.block.uitls.SecurityUtils;
import com.zx.system.block.dao.SysDictDataMapper;
import com.zx.system.block.event.DictDataChangeEvent;
import com.zx.system.block.mapstruct.DictDataMapStructMapper;
import com.zx.system.block.model.SysDictData;
import com.zx.system.block.param.DictDataParam;
import com.zx.system.block.service.ISysDictDataService;
import com.zx.system.block.utils.SystemNoUtils;
import com.zx.system.block.vo.SysDictDataVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * description: 业务层字典数据服务实现 <br>
 * create: 2025-11-18
 * </p>
 *
 * @author zhou xun
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysDictDataServiceImpl implements ISysDictDataService {
    private final SysDictDataMapper sysDictDataMapper;
    private final RedisBlockService redisBlockService;
    private final ApplicationEventPublisher eventPublisher;

    /**
     * 查询字典数据列表
     *
     * @param dictDataParam 字典数据参数
     * @return {@link ListWrapper<SysDictData>}
     * @author zhou xun
     * @since 2025-11-18
     */
    @Override
    public ListWrapper<SysDictData> selectDictDataList(DictDataParam dictDataParam) {
        ListWrapper<SysDictData> result = new ListWrapper<>();
        try {
            // 验证字典数据状态
            if (dictDataParam.getStatus() != null) {
                StatusEnum enumByCode = StatusEnum.getEnumByCode(dictDataParam.getStatus());
                if (null == enumByCode) {
                    result.fail("传入的字典数据状态错误!");
                    return result;
                }
            }

            List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataList(
                    TenantContextHolder.getTenantId(),
                    dictDataParam.getDictType(),
                    dictDataParam.getDictLabel(),
                    dictDataParam.getStatus(),
                    dictDataParam.getCreateTimeStart(),
                    dictDataParam.getCreateTimeEnd());
            if (sysDictDataList != null) {
                result.setData(sysDictDataList);
            }
        } catch (Exception e) {
            log.error("查询字典数据列表时发生错误", e);
            result.fail("查询字典数据列表时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 分页查询字典数据列表
     *
     * @param dictDataParam 字典数据参数
     * @return {@link PageWrapper <SysDictData>}
     * @author zhou xun
     * @since 2025-11-18
     */
    @Override
    public PageWrapper<SysDictData> selectDictDataListByPage(DictDataParam dictDataParam) {
        PageWrapper<SysDictData> result = new PageWrapper<>();
        try {
            // 验证字典数据状态
            if (dictDataParam.getStatus() != null) {
                StatusEnum enumByCode = StatusEnum.getEnumByCode(dictDataParam.getStatus());
                if (null == enumByCode) {
                    result.fail("传入的字典数据状态错误!");
                    return result;
                }
            }

            PageInfo pageInfo = new PageInfo(dictDataParam.getPageNum(), dictDataParam.getPageSize());
            dictDataParam.setPageNum(pageInfo.getPageNum());
            dictDataParam.setPageSize(pageInfo.getPageSize());

            Long count = sysDictDataMapper.getDictDataListCount(
                    TenantContextHolder.getTenantId(),
                    dictDataParam.getDictType(),
                    dictDataParam.getDictLabel(),
                    dictDataParam.getStatus(),
                    dictDataParam.getCreateTimeStart(),
                    dictDataParam.getCreateTimeEnd());

            if (count > 0) {
                List<SysDictData> sysDictDataList = sysDictDataMapper.getDictDataListByPage(
                        TenantContextHolder.getTenantId(),
                        dictDataParam.getDictType(),
                        dictDataParam.getDictLabel(),
                        dictDataParam.getStatus(),
                        dictDataParam.getCreateTimeStart(),
                        dictDataParam.getCreateTimeEnd(),
                        dictDataParam.getPageNum(),
                        dictDataParam.getPageSize());

                result.setData(sysDictDataList);
            }
            result.setTotal(count);
            result.setCurrentPageNum(dictDataParam.getPageNum());
            result.setTotalPage(pageInfo);
        } catch (Exception e) {
            log.error("分页查询字典数据列表时发生错误", e);
            result.fail("分页查询字典数据列表时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 查询字典数据列表VO
     *
     * @param dictDataParam 字典数据参数
     * @return {@link ListWrapper<SysDictDataVO>}
     * @author zhou xun
     * @since 2025-11-18
     */
    @Override
    public ListWrapper<SysDictDataVO> selectDictDataVOList(DictDataParam dictDataParam) {
        ListWrapper<SysDictDataVO> result = new ListWrapper<>();
        try {
            // 获取字典数据列表
            ListWrapper<SysDictData> listWrapper = selectDictDataList(dictDataParam);

            // 验证请求是否成功或数据是否为空
            if (listWrapper.verifyFail()) {
                result.fail(listWrapper.getMsg());
                return result;
            }

            if (null != listWrapper.getData() && !listWrapper.getData().isEmpty()) {
                // 转换并处理数据
                List<SysDictDataVO> processedData = listWrapper.getData().stream()
                        .map(DictDataMapStructMapper.INSTANCE::sysDictDataToSysDictDataVO)
                        .collect(Collectors.toList());

                result.setData(processedData);
            }
        } catch (Exception e) {
            log.error("查询字典数据列表VO时发生错误", e);
            result.fail("查询字典数据列表VO时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 分页查询字典数据列表VO
     *
     * @param dictDataParam 字典数据参数
     * @return {@link PageWrapper<SysDictDataVO>}
     * @author zhou xun
     * @since 2025-11-18
     */
    @Override
    public PageWrapper<SysDictDataVO> selectDictDataVOListByPage(DictDataParam dictDataParam) {
        PageWrapper<SysDictDataVO> result = new PageWrapper<>();
        try {
            // 获取字典数据列表
            PageWrapper<SysDictData> pageWrapper = selectDictDataListByPage(dictDataParam);

            // 验证请求是否成功或数据是否为空
            if (pageWrapper.verifyFail()) {
                result.fail(pageWrapper.getMsg());
                return result;
            }
            if (null != pageWrapper.getData() && !pageWrapper.getData().isEmpty()) {
                // 转换并处理数据
                List<SysDictDataVO> processedData = pageWrapper.getData().stream()
                        .map(DictDataMapStructMapper.INSTANCE::sysDictDataToSysDictDataVO)
                        .collect(Collectors.toList());

                result.setData(processedData);
                result.setTotal(pageWrapper.getTotal());
                result.setCurrentPageNum(pageWrapper.getCurrentPageNum());
            }
        } catch (Exception e) {
            log.error("分页查询字典数据列表VO时发生错误", e);
            result.fail("分页查询字典数据列表VO时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 新增字典数据
     *
     * @param dictDataParam 字典数据参数
     * @return {@link ResponseWrapper}
     * @author zhou xun
     * @since 2025-11-18
     */
    @Override
    public ResponseWrapper addDictData(DictDataParam dictDataParam) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            // 验证字典数据状态
            StatusEnum statusEnum = StatusEnum.getEnumByCode(dictDataParam.getStatus());
            if (null == statusEnum) {
                result.fail("传入的字典数据状态错误!");
                return result;
            }

            SysDictData sysDictData = DictDataMapStructMapper.INSTANCE.dictDataParamToSysDictData(dictDataParam);
            // 设置id
            sysDictData.setId(SystemNoUtils.generateSystemId());
            // 设置租户id
            sysDictData.setTenantId(TenantContextHolder.getTenantId());
            sysDictData.setCreateBy(SecurityUtils.getUserId());
            sysDictData.setCreateTime(LocalDateTime.now());
            sysDictDataMapper.insert(sysDictData);

            // 发布字典数据变更事件
            DictDataChangeEvent event = new DictDataChangeEvent(this, dictDataParam.getDictType(), "ADD");
            eventPublisher.publishEvent(event);
        } catch (Exception e) {
            log.error("新增字典数据时发生错误", e);
            result.fail("新增字典数据时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 编辑字典数据
     *
     * @param dictDataParam 字典数据参数
     * @return {@link ResponseWrapper}
     * @author zhou xun
     * @since 2025-11-18
     */
    @Override
    public ResponseWrapper editDictData(DictDataParam dictDataParam) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            // 验证字典数据状态
            StatusEnum statusEnum = StatusEnum.getEnumByCode(dictDataParam.getStatus());
            if (null == statusEnum) {
                result.fail("传入的字典数据状态错误!");
                return result;
            }

            // 检查字典数据是否存在
            SysDictData existingDictData = sysDictDataMapper.selectByPrimaryKey(dictDataParam.getId());
            if (existingDictData == null) {
                result.fail("字典数据不存在!");
                return result;
            }

            SysDictData sysDictData = DictDataMapStructMapper.INSTANCE.dictDataParamToSysDictData(dictDataParam);
            sysDictData.setUpdateBy(SecurityUtils.getUserId());
            sysDictData.setUpdateTime(LocalDateTime.now());
            sysDictDataMapper.updateByPrimaryKeySelective(sysDictData);

            // 发布字典数据变更事件
            DictDataChangeEvent event = new DictDataChangeEvent(this, dictDataParam.getDictType(), "UPDATE");
            eventPublisher.publishEvent(event);
        } catch (Exception e) {
            log.error("编辑字典数据时发生错误", e);
            result.fail("编辑字典数据时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 编辑字典数据状态
     *
     * @param id     字典数据Id
     * @param status 字典数据状态 0停用 1 启用
     * @return {@link ResponseWrapper}
     * @author zhou xun
     * @since 2025-11-18
     */
    @Override
    public ResponseWrapper editDictDataStatus(String id, Integer status) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            // 验证字典数据状态
            StatusEnum statusEnum = StatusEnum.getEnumByCode(status);
            if (null == statusEnum) {
                result.fail("传入的字典数据状态错误!");
                return result;
            }

            // 验证字典数据是否存在
            SysDictData selectByPrimaryKey = sysDictDataMapper.selectByPrimaryKey(id);
            if (null == selectByPrimaryKey) {
                result.fail("传入的字典数据信息不存在!");
                return result;
            }

            SysDictData sysDictData = new SysDictData();
            sysDictData.setId(id);
            sysDictData.setStatus(status);
            sysDictData.setUpdateBy(SecurityUtils.getUserId());
            sysDictData.setUpdateTime(LocalDateTime.now());
            sysDictDataMapper.updateByPrimaryKeySelective(sysDictData);

            // 发布字典数据变更事件
            DictDataChangeEvent event = new DictDataChangeEvent(this, selectByPrimaryKey.getDictType(), "UPDATE");
            eventPublisher.publishEvent(event);
        } catch (Exception e) {
            log.error("编辑字典数据状态时发生错误", e);
            result.fail("编辑字典数据状态时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 删除字典数据
     *
     * @param dictDataId 字典数据Id
     * @return {@link ResponseWrapper}
     * @author zhou xun
     * @since 2025-11-18
     */
    @Override
    public ResponseWrapper deleteDictData(String dictDataId) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            // 验证字典数据是否存在
            SysDictData selectByPrimaryKey = sysDictDataMapper.selectByPrimaryKey(dictDataId);
            if (null == selectByPrimaryKey) {
                result.fail("传入的字典数据信息不存在!");
                return result;
            }

            sysDictDataMapper.deleteByPrimaryKey(dictDataId);

            // 发布字典数据变更事件
            DictDataChangeEvent event = new DictDataChangeEvent(this, selectByPrimaryKey.getDictType(), "DELETE");
            eventPublisher.publishEvent(event);
        } catch (Exception e) {
            log.error("删除字典数据时发生错误", e);
            result.fail("删除字典数据时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 根据字典类型查询启用的字典数据列表VO
     *
     * @param dictType 字典类型
     * @return {@link ListWrapper<SysDictDataVO>} 字典数据列表VO
     * @author zhou xun
     * @since 2025-11-19
     */
    @Override
    public ListWrapper<SysDictDataVO> selectEnableDictDataVOListByType(String dictType) {
        ListWrapper<SysDictDataVO> result = new ListWrapper<>();
        try {
            // 先尝试从VO缓存获取
            String voCacheKey = CacheConstants.DICT_DATA_KEY + dictType;
            List<SysDictDataVO> cachedVOData = redisBlockService.getCachedObject(voCacheKey, List.class);
            if (cachedVOData != null) {
                result.setData(cachedVOData);
                return result;
            }

            // 尝试从共享基础数据缓存获取
            String baseCacheKey = CacheConstants.DICT_DATA_KEY + "base:" + dictType;
            List<SysDictData> cachedBaseData = redisBlockService.getCachedObject(baseCacheKey, List.class);
            if (cachedBaseData != null) {
                // 转换为基础VO数据并缓存
                List<SysDictDataVO> dictDataVOList = cachedBaseData.stream()
                        .filter(data -> StatusEnum.ENABLE.getCode().equals(data.getStatus()))
                        .map(DictDataMapStructMapper.INSTANCE::sysDictDataToSysDictDataVO)
                        .collect(Collectors.toList());

                result.setData(dictDataVOList);

                // 存入VO缓存
                redisBlockService.setCacheObject(voCacheKey, dictDataVOList, CacheConstants.DEFAULT_EXPIRE_MINUTES, CacheConstants.DEFAULT_EXPIRE_TIME_UNIT);
                return result;
            }

            List<SysDictData> dictDataList = sysDictDataMapper.selectDictDataByType(dictType, TenantContextHolder.getTenantId());
            if (null != dictDataList && !dictDataList.isEmpty()) {
                // 过滤启用状态的数据
                List<SysDictDataVO> dictDataVOList = dictDataList.stream()
                        .filter(data -> StatusEnum.ENABLE.getCode().equals(data.getStatus()))
                        .map(DictDataMapStructMapper.INSTANCE::sysDictDataToSysDictDataVO)
                        .collect(Collectors.toList());
                result.setData(dictDataVOList);

                // 存入Redis缓存，设置过期时间30分钟
                redisBlockService.setCacheObject(voCacheKey, dictDataVOList, CacheConstants.DEFAULT_EXPIRE_MINUTES, CacheConstants.DEFAULT_EXPIRE_TIME_UNIT);
                // 同时存入共享基础数据缓存
                redisBlockService.setCacheObject(baseCacheKey, dictDataList, CacheConstants.DEFAULT_EXPIRE_MINUTES, CacheConstants.DEFAULT_EXPIRE_TIME_UNIT);
            }
            // 恢复原有风格，不显式处理空数据情况
        } catch (Exception e) {
            log.error("根据字典类型查询启用的字典数据列表VO时发生错误", e);
            result.fail("查询字典数据失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 批量根据字典类型查询启用的字典数据列表VO
     *
     * @param dictTypes 字典类型列表
     * @return {@link ObjectWrapper<Map<String, List<SysDictDataVO>>>} 字典类型和字典数据列表VO的映射包装
     * @author zhou xun
     * @since 2025-11-19
     */
    @Override
    public ObjectWrapper<Map<String, List<SysDictDataVO>>> selectEnableDictDataVOListByTypes(List<String> dictTypes) {
        ObjectWrapper<Map<String, List<SysDictDataVO>>> result = new ObjectWrapper<>();
        try {
            // 构建批量查询缓存键
            String batchCacheKey = CacheConstants.DICT_DATA_KEY + "batch:" + String.join(",", dictTypes);

            // 先尝试从缓存获取
            Map<String, List<SysDictDataVO>> cachedData = redisBlockService.getCachedObject(batchCacheKey, Map.class);
            if (cachedData != null) {
                result.setData(cachedData);
                return result;
            }

            // 尝试从共享基础数据批量缓存获取
            String baseBatchCacheKey = CacheConstants.DICT_DATA_KEY + "base_batch:" + String.join(",", dictTypes);
            Map<String, List<SysDictData>> cachedBaseData = redisBlockService.getCachedObject(baseBatchCacheKey, Map.class);
            if (cachedBaseData != null) {
                // 转换为基础VO数据并缓存
                Map<String, List<SysDictDataVO>> resultMap = cachedBaseData.entrySet().stream()
                        .collect(Collectors.toMap(
                                Map.Entry::getKey,
                                entry -> entry.getValue().stream()
                                        .filter(data -> StatusEnum.ENABLE.getCode().equals(data.getStatus()))
                                        .map(DictDataMapStructMapper.INSTANCE::sysDictDataToSysDictDataVO)
                                        .collect(Collectors.toList())
                        ));

                result.setData(resultMap);

                // 存入批量VO缓存
                redisBlockService.setCacheObject(batchCacheKey, resultMap, CacheConstants.DEFAULT_EXPIRE_MINUTES, CacheConstants.DEFAULT_EXPIRE_TIME_UNIT);
                return result;
            }

            // 一次性查询所有字典类型的数据
            List<SysDictData> allDictDataList = sysDictDataMapper.selectDictDataByTypes(dictTypes, TenantContextHolder.getTenantId());
            if (null != allDictDataList && !allDictDataList.isEmpty()) {
                // 按字典类型分组并过滤启用状态的数据
                Map<String, List<SysDictDataVO>> resultMap = allDictDataList.stream()
                        .filter(data -> StatusEnum.ENABLE.getCode().equals(data.getStatus()))
                        .collect(Collectors.groupingBy(
                                SysDictData::getDictType,
                                Collectors.mapping(DictDataMapStructMapper.INSTANCE::sysDictDataToSysDictDataVO, Collectors.toList())
                        ));
                result.setData(resultMap);

                // 存入Redis缓存，设置过期时间30分钟
                redisBlockService.setCacheObject(batchCacheKey, resultMap, CacheConstants.DEFAULT_EXPIRE_MINUTES, CacheConstants.DEFAULT_EXPIRE_TIME_UNIT);
                // 同时存入共享基础数据批量缓存
                Map<String, List<SysDictData>> baseResultMap = allDictDataList.stream()
                        .collect(Collectors.groupingBy(SysDictData::getDictType));
                redisBlockService.setCacheObject(baseBatchCacheKey, baseResultMap, CacheConstants.DEFAULT_EXPIRE_MINUTES, CacheConstants.DEFAULT_EXPIRE_TIME_UNIT);
            }
        } catch (Exception e) {
            log.error("批量根据字典类型查询启用的字典数据列表VO时发生错误", e);
            result.fail("查询字典数据失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 批量根据字典类型查询启用的字典数据列表DTO
     *
     * @param dictType
     * @return {@link ListWrapper< DictDataDTO >}
     * @author zhou  xun
     * @since 2025-11-21
     */
    @Override
    public ListWrapper<DictDataDTO> selectEnableDictDataDTOListByType(String dictType) {
        ListWrapper<DictDataDTO> result = new ListWrapper<>();
        try {
            // 先尝试从DTO缓存获取
            String dtoCacheKey = CacheConstants.DICT_DATA_KEY + "dto:" + dictType;
            List<DictDataDTO> cachedDTOData = redisBlockService.getCachedObject(dtoCacheKey, List.class);
            if (cachedDTOData != null) {
                result.setData(cachedDTOData);
                return result;
            }

            // 尝试从共享基础数据缓存获取
            String baseCacheKey = CacheConstants.DICT_DATA_KEY + "base:" + dictType;
            List<SysDictData> cachedBaseData = redisBlockService.getCachedObject(baseCacheKey, List.class);
            if (cachedBaseData != null) {
                // 转换为基础DTO数据并缓存
                List<DictDataDTO> dtoList = cachedBaseData.stream()
                        .filter(data -> StatusEnum.ENABLE.getCode().equals(data.getStatus()))
                        .map(DictDataMapStructMapper.INSTANCE::sysDictDataToDictDataDTO)
                        .collect(Collectors.toList());

                result.setData(dtoList);

                // 存入DTO缓存
                redisBlockService.setCacheObject(dtoCacheKey, dtoList, CacheConstants.DEFAULT_EXPIRE_MINUTES, CacheConstants.DEFAULT_EXPIRE_TIME_UNIT);
                return result;
            }

            List<SysDictData> dictDataList = sysDictDataMapper.selectDictDataByType(dictType, TenantContextHolder.getTenantId());
            if (null != dictDataList && !dictDataList.isEmpty()) {
                List<DictDataDTO> dtoList = dictDataList.stream()
                        .filter(data -> StatusEnum.ENABLE.getCode().equals(data.getStatus()))
                        .map(DictDataMapStructMapper.INSTANCE::sysDictDataToDictDataDTO)
                        .collect(Collectors.toList());
                result.setData(dtoList);

                // 存入DTO缓存
                redisBlockService.setCacheObject(dtoCacheKey, dtoList, CacheConstants.DEFAULT_EXPIRE_MINUTES, CacheConstants.DEFAULT_EXPIRE_TIME_UNIT);
                // 同时存入共享基础数据缓存
                redisBlockService.setCacheObject(baseCacheKey, dictDataList, CacheConstants.DEFAULT_EXPIRE_MINUTES, CacheConstants.DEFAULT_EXPIRE_TIME_UNIT);
            }
        } catch (Exception e) {
            log.error("批量根据字典类型查询启用的字典数据列表DTO时发生错误", e);
        }
        return result;
    }

    /**
     * 批量根据字典类型查询启用的字典数据列表DTO
     *
     * @param dictTypes 字典类型列表
     * @return {@link ObjectWrapper<Map<String, List<DictDataDTO>>>} 字典类型和字典数据列表DTO的映射包装
     * @author zhou xun
     * @since 2025-11-19
     */
    @Override
    public ObjectWrapper<Map<String, List<DictDataDTO>>> selectEnableDictDataDTOListByTypes(List<String> dictTypes) {
        ObjectWrapper<Map<String, List<DictDataDTO>>> result = new ObjectWrapper<>();
        try {
            // 构建批量查询缓存键
            String dtoBatchCacheKey = CacheConstants.DICT_DATA_KEY + "dto_batch:" + String.join(",", dictTypes);

            // 先尝试从DTO缓存获取
            Map<String, List<DictDataDTO>> cachedData = redisBlockService.getCachedObject(dtoBatchCacheKey, Map.class);
            if (cachedData != null) {
                result.setData(cachedData);
                return result;
            }

            // 尝试从共享基础数据批量缓存获取
            String baseBatchCacheKey = CacheConstants.DICT_DATA_KEY + "base_batch:" + String.join(",", dictTypes);
            Map<String, List<SysDictData>> cachedBaseData = redisBlockService.getCachedObject(baseBatchCacheKey, Map.class);
            if (cachedBaseData != null) {
                // 转换为基础DTO数据并缓存
                Map<String, List<DictDataDTO>> resultMap = cachedBaseData.entrySet().stream()
                        .collect(Collectors.toMap(
                                Map.Entry::getKey,
                                entry -> entry.getValue().stream()
                                        .filter(data -> StatusEnum.ENABLE.getCode().equals(data.getStatus()))
                                        .map(DictDataMapStructMapper.INSTANCE::sysDictDataToDictDataDTO)
                                        .collect(Collectors.toList())
                        ));

                result.setData(resultMap);

                // 存入DTO批量缓存
                redisBlockService.setCacheObject(dtoBatchCacheKey, resultMap, CacheConstants.DEFAULT_EXPIRE_MINUTES, CacheConstants.DEFAULT_EXPIRE_TIME_UNIT);
                return result;
            }

            // 一次性查询所有字典类型数据
            List<SysDictData> allDictDataList = sysDictDataMapper.selectDictDataByTypes(dictTypes, TenantContextHolder.getTenantId());
            if (null != allDictDataList && !allDictDataList.isEmpty()) {
                // 按字典类型分组并过滤启用状态的数据
                Map<String, List<DictDataDTO>> resultMap = allDictDataList.stream()
                        .filter(data -> StatusEnum.ENABLE.getCode().equals(data.getStatus()))
                        .collect(Collectors.groupingBy(
                                SysDictData::getDictType,
                                Collectors.mapping(DictDataMapStructMapper.INSTANCE::sysDictDataToDictDataDTO, Collectors.toList())
                        ));
                result.setData(resultMap);

                // 存入Redis缓存，设置过期时间30分钟
                redisBlockService.setCacheObject(dtoBatchCacheKey, resultMap, CacheConstants.DEFAULT_EXPIRE_MINUTES, CacheConstants.DEFAULT_EXPIRE_TIME_UNIT);
                // 同时存入共享基础数据批量缓存
                Map<String, List<SysDictData>> baseResultMap = allDictDataList.stream()
                        .collect(Collectors.groupingBy(SysDictData::getDictType));
                redisBlockService.setCacheObject(baseBatchCacheKey, baseResultMap, CacheConstants.DEFAULT_EXPIRE_MINUTES, CacheConstants.DEFAULT_EXPIRE_TIME_UNIT);
            }
        } catch (Exception e) {
            log.error("批量根据字典类型查询启用的字典数据列表DTO时发生错误", e);
            result.fail("批量根据字典类型查询启用的字典数据列表DTO时发生错误: " + e.getMessage());
        }
        return result;
    }
}